package com.zhousb.deviceManager.security;

import com.zhousb.deviceManager.model.entity.SysRole;
import com.zhousb.deviceManager.model.entity.SysUser;
import com.zhousb.deviceManager.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;

/**
 * @author JoinIn
 * @date 2023/8/16 16:20
 */

@Service
public class JwtUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getByUsername(username);
        if (sysUser != null) {
            List<SysRole> roles = sysUserService.listRoleByUserId(sysUser.getId());
            HashSet<SysRole> roleSet = new HashSet<>(roles);
            return new JwtUser(sysUser.getId(), sysUser.getUserName(), sysUser.getPassword(),
                    roleSet, sysUser.getRealName(), sysUser.getUserTel(),sysUser.getTenantId());
        } else {
            throw new UsernameNotFoundException("User not found with username: " + username);
        }
    }
}
